package com.zdkj.subway.stm.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zdkj.admin.api.entity.SysDictItem;
import com.zdkj.common.core.constant.CommonConstants;
import com.zdkj.common.core.constant.SecurityConstants;
import com.zdkj.common.core.util.R;
import com.zdkj.common.log.annotation.SysLog;
import com.zdkj.common.security.util.ObjectUtils;
import com.zdkj.subway.stm.constant.StmConstans;
import com.zdkj.subway.stm.dto.out.SwStTvmIncomeSettleDto;
import com.zdkj.subway.stm.entity.*;
import com.zdkj.subway.stm.fegin.SubwayCheckService;
import com.zdkj.subway.stm.fegin.SystemUserService;
import com.zdkj.subway.stm.mapper.SwStInputCashboxUninstalledMapper;
import com.zdkj.subway.stm.service.*;
import com.zdkj.subway.stm.util.DateUtilStm;
import com.zdkj.subway.stm.util.JdbcUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.time.LocalDate;
import java.util.stream.Collectors;


/**
 * 钱箱未卸载
 *
 * @author songtuo
 * @date 2020-07-08 09:33:50
 */
@RestController
@AllArgsConstructor
@RequestMapping("/swstinputcashboxuninstalled")
@Api(value = "swstinputcashboxuninstalled", tags = "钱箱未卸载管理")
@Slf4j
public class SwStInputCashboxUninstalledController {

    private final SwStInputCashboxUninstalledService swStInputCashboxUninstalledService;
    @Resource
    private final SwStInputCashboxUninstalledMapper swStInputCashboxUninstalledMapper;

    private final SwStTvmCheckDetailService swStTvmCheckDetailService;

    @Autowired
    SwStTvmCheckDetailCoinService swStTvmCheckDetailCoinService;
    @Autowired
    SwStTvmCheckDetailCoinChangeService swStTvmCheckDetailCoinChangeService;
    @Autowired
    SwStTvmCheckDetailPaperService swStTvmCheckDetailPaperService;
    @Autowired
    SwStTvmCheckDetailPaperChangeService swStTvmCheckDetailPaperChangeService;
    @Autowired
    SwStTvmCheckDetailWasteService stTvmCheckDetailWasteService;

    private final SystemUserService systemUserService;
    private final SubwayCheckService subwayCheckService;


    /**
     * 分页查询
     *
     * @param page                        分页对象
     * @param swStInputCashboxUninstalled 钱箱未卸载
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page")
    public R getSwStInputCashboxUninstalledPage(Page page, SwStInputCashboxUninstalled swStInputCashboxUninstalled) {
        //未卸载日期
        List<String> dateCondition1 = swStInputCashboxUninstalled.getDates1();
        //卸载日期
        List<String> dateCondition2 = swStInputCashboxUninstalled.getDates2();
        SwStInputCashboxUninstalled swStInputCashboxUninstalledObj = ObjectUtils.getDefaultObj(SwStInputCashboxUninstalled.class);
        swStInputCashboxUninstalled.setLineCode(swStInputCashboxUninstalledObj.getLineCode());
        swStInputCashboxUninstalled.setStationCode(swStInputCashboxUninstalledObj.getStationCode());

        QueryWrapper queryWrapper = Wrappers.query(swStInputCashboxUninstalled);
        if (ObjectUtil.isNotEmpty(dateCondition1)) {
            queryWrapper.between("UNINSTALLED_DATE", dateCondition1.get(0), dateCondition1.get(1));
        }
        if (ObjectUtil.isNotEmpty(dateCondition2)) {
            queryWrapper.between("UNINSTALL_DATE", dateCondition2.get(0), dateCondition2.get(1));
        }
        queryWrapper.orderByDesc("UNINSTALLED_DATE");
        return R.ok(swStInputCashboxUninstalledService.page(page, queryWrapper));
    }


    /**
     * 通过id查询钱箱未卸载
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}")
    public R getById(@PathVariable("id") Integer id) {
        return R.ok(swStInputCashboxUninstalledService.getById(id));
    }

    /**
     * 新增钱箱未卸载
     *
     * @param swStInputCashboxUninstalled 钱箱未卸载
     * @return R
     */
    @ApiOperation(value = "新增钱箱未卸载", notes = "新增钱箱未卸载")
    @SysLog("新增钱箱未卸载")
    @PostMapping
    @PreAuthorize("@pms.hasPermission('swstinputcashboxuninstalled_add')")
    public R save(@RequestBody SwStInputCashboxUninstalled swStInputCashboxUninstalled) {
        //这个接口暂时用不到 直接在日清点数据的时候同步模块
        SwStInputCashboxUninstalled swStInputCashboxUninstalledObj = ObjectUtils.getDefaultObj(SwStInputCashboxUninstalled.class);
        BeanUtil.copyProperties(swStInputCashboxUninstalledObj, swStInputCashboxUninstalled, CopyOptions.create().setIgnoreNullValue(true));
        return R.ok(swStInputCashboxUninstalledService.save(swStInputCashboxUninstalled));
    }

    /**
     * 修改钱箱未卸载
     *
     * @param swStInputCashboxUninstalled 钱箱未卸载
     * @return R
     */
    @ApiOperation(value = "修改钱箱未卸载", notes = "修改钱箱未卸载")
    @SysLog("修改钱箱未卸载")
    @PutMapping
    @PreAuthorize("@pms.hasPermission('swstinputcashboxuninstalled_edit')")
    @Transactional(rollbackFor = Exception.class)
    public R updateById(@RequestBody SwStInputCashboxUninstalled swStInputCashboxUninstalled) {

        try {
            String lineCode = swStInputCashboxUninstalled.getLineCode();
            String stationCode = swStInputCashboxUninstalled.getStationCode();
            String tvmCode = swStInputCashboxUninstalled.getTvmCode();
            String moneyBoxType = swStInputCashboxUninstalled.getMoneyBoxType();//钱箱类型
            //String moneyBoxCode = swStInputCashboxUninstalled.getMoneyBoxCode();//钱箱编号
            LocalDate uninstalledDate = swStInputCashboxUninstalled.getUninstalledDate();//未卸载日期
            LocalDate uninstallDate = swStInputCashboxUninstalled.getUninstallDate();//实际卸载日期
			if(uninstallDate!=null){  //20241105 增加入账日期=实际卸载日期
				swStInputCashboxUninstalled.setPostDate(uninstallDate);
			}

            BigDecimal uninstallAmount = swStInputCashboxUninstalled.getUninstallAmount();//实际卸载金额
			

 /*  20241105  调整为车站模块未卸载保持原样，也不进行修改。收入审核只修改TVM卸载状态，其他金额也不变。
			  假设10号纸币回收箱未卸载，13号实际卸载  入账时间等于实际卸载金额不可更改
1. 车站TVM钱箱清点记录 10号的纸币回收箱未卸载，按实际录入并选择未卸载原因
2. 车站钱箱未卸载模块，车站录入实际卸载时间13号和实际卸载金额 100元。其他操作都不做。入账时间需要默认设置为实际卸载时间不更改
3. 未卸载页面增加系统金额模块，接口获取实际卸载钱箱系统金额数据更新显示并计算差异。
4. 收入审核页面卸载状态在车站录入实际卸载金额后状态变更为已卸载/未卸载   10号的清点记录  只改状态

-- 只需要修改收入审核TVM单台和分钱箱的状态即可
*/

           /* 原有的代码
			swStTvmCheckDetail = swStTvmCheckDetailService.getOne(Wrappers.query(swStTvmCheckDetail));//钱箱清点主表
            if(ObjectUtil.isNotEmpty(swStTvmCheckDetail)){
                Integer checkDetailMainId =  swStTvmCheckDetail.getId();
                String tableName  = "";
                if("硬币回收箱".equals(moneyBoxType)){//硬币回收箱
                    tableName="sw_st_tvm_check_detail_coin";
                    moneyBoxType = "1";
                }else if("硬币补充箱".equals(moneyBoxType)){//硬币找零箱
                    tableName="sw_st_tvm_check_detail_coin_change";
                    moneyBoxType = "2";
                }else if("纸币回收箱".equals(moneyBoxType)){  //纸币回收箱
                    tableName="sw_st_tvm_check_detail_paper";
                    moneyBoxType = "3";
                }else if("纸币找零箱".equals(moneyBoxType)){//纸币找零箱
                    tableName="sw_st_tvm_check_detail_paper_change";
                    moneyBoxType = "4";
                }else if("废钞箱".equals(moneyBoxType)){//废钞箱
                    tableName="sw_st_tvm_check_detail_waste";
                    moneyBoxType = "5";
                }
                //根据钱箱类型更新相对应的子表信息-----子表的未卸载原因改为无，卸载金额为输入的金额，非标准币金额为0， 2021-06-23 去掉钱箱编号更新
                //String sqlCheckDetailsBox = "update "+tableName+" set  CASHBOX_CODE = '"+moneyBoxCode+"', REAL_AMOUNT="+uninstallAmount+",update_time=now(),unload_case='3' where RELATION_ID="+checkDetailMainId+" and del_flag='0'";
				String sqlCheckDetailsBox = "update "+tableName+" set  REAL_AMOUNT="+uninstallAmount+",update_time=now(),unload_case='3' where RELATION_ID="+checkDetailMainId+" and del_flag='0'";
                //TODO  调用JDBCUtil执行
                JdbcUtil.exeSqlCrud(sqlCheckDetailsBox);//更新钱箱子表信息
                //清点总金额
                BigDecimal checkAmount = new BigDecimal("0.00");

                //----更新对应主表的清点总金额
                SwStTvmCheckDetailCoin detailCoin = swStTvmCheckDetailCoinService.getOne(Wrappers.<SwStTvmCheckDetailCoin>lambdaQuery().eq(SwStTvmCheckDetailCoin::getRelationId, checkDetailMainId));
                if(ObjectUtil.isNotEmpty(detailCoin)){
                    checkAmount = checkAmount.add(detailCoin.getRealAmount());
                }
                SwStTvmCheckDetailCoinChange detailCoinChange = swStTvmCheckDetailCoinChangeService.getOne(Wrappers.<SwStTvmCheckDetailCoinChange>lambdaQuery().eq(SwStTvmCheckDetailCoinChange::getRelationId, checkDetailMainId));
                if(ObjectUtil.isNotEmpty(detailCoinChange)){
                    checkAmount = checkAmount.add(detailCoinChange.getRealAmount());
                }
                SwStTvmCheckDetailPaper detailPaper = swStTvmCheckDetailPaperService.getOne(Wrappers.<SwStTvmCheckDetailPaper>lambdaQuery().eq(SwStTvmCheckDetailPaper::getRelationId, checkDetailMainId));
                if(ObjectUtil.isNotEmpty(detailPaper)){
                    checkAmount = checkAmount.add(detailPaper.getRealAmount());
                }
                SwStTvmCheckDetailPaperChange detailPaperChange = swStTvmCheckDetailPaperChangeService.getOne(Wrappers.<SwStTvmCheckDetailPaperChange>lambdaQuery().eq(SwStTvmCheckDetailPaperChange::getRelationId, checkDetailMainId));
                if(ObjectUtil.isNotEmpty(detailPaperChange)){
                    checkAmount = checkAmount.add(detailPaperChange.getRealAmount());
                }
                SwStTvmCheckDetailWaste detailWaste = stTvmCheckDetailWasteService.getOne(Wrappers.<SwStTvmCheckDetailWaste>lambdaQuery().eq(SwStTvmCheckDetailWaste::getRelationId, checkDetailMainId));
                if(ObjectUtil.isNotEmpty(detailWaste)){
                    checkAmount = checkAmount.add(detailWaste.getRealAmount());
                }
                swStTvmCheckDetail.setCheckAmount(checkAmount);
                swStTvmCheckDetailService.updateById(swStTvmCheckDetail);

                //-- TODO 如果tvm收入结算未提交，钱箱就已经卸载下来了，就不需要更新收入结算和审核表
                if(!"0".equals(swStTvmCheckDetail.getApprovalStatus())){
                    //---钱箱卸载后更新收入结算清点金额、现金实收金额
                    SwStTvmIncomeSettleDto swStTvmIncomeSettleDto = new SwStTvmIncomeSettleDto();
                    swStTvmIncomeSettleDto.setLineCode(swStTvmCheckDetail.getLineCode());
                    swStTvmIncomeSettleDto.setStationCode(swStTvmCheckDetail.getStationCode());
                    swStTvmIncomeSettleDto.setTvmCode(swStTvmCheckDetail.getTvmCode());
                    swStTvmIncomeSettleDto.setRecordTime(DateUtilStm.LocalDateToUdate(swStTvmCheckDetail.getRevenueTime()));
                    Map<String, Object> stringObjectMap = swStInputCashboxUninstalledMapper.selectCheckAmount(swStTvmIncomeSettleDto);
                    if(ObjectUtil.isNotEmpty(stringObjectMap)){
                        //补币已经乘过100了
                        BigDecimal supplementMoney = new BigDecimal(String.valueOf(stringObjectMap.get("supplementMoney")));
                        //手工清出已经乘过100了
                        BigDecimal handOutMoney = new BigDecimal(String.valueOf(stringObjectMap.get("handOutMoney")));
                        //系统金额已经乘过100了
                        BigDecimal systemMoney = new BigDecimal(String.valueOf(stringObjectMap.get("systemMoney")));
                        //卸载清点金额(收入结算不需要乘100)
                        swStTvmIncomeSettleDto.setCheckAmount(checkAmount);
                        //计算实收金额  卸载清点金额-补币+手工清出(收入结算不需要乘100)
                        swStTvmIncomeSettleDto.setCashReceiptAmount(checkAmount.multiply(new BigDecimal("100")).subtract(supplementMoney).add(handOutMoney).divide(new BigDecimal("100")));
                        //fegin调用
                        subwayCheckService.updateUnAmount(SecurityConstants.FROM_IN,swStTvmIncomeSettleDto);

                        //---更新TVM收入审核主表
                        String sqlAmountDefference = "update sw_au_tvm_amount_defference set BOX_UNINSTALL_STATUS = '3', actual_money = " + swStTvmIncomeSettleDto.getCashReceiptAmount() + " *100, diff_money = " + swStTvmIncomeSettleDto.getCashReceiptAmount() + " *100 - " + systemMoney + ", update_time=now()\n" +
                                "\t\t  where  line_code = '"+lineCode+"' and station_code = '"+stationCode+"' and tvm_code = '"+tvmCode+"' and RECORD_TIME = DATE_FORMAT('"+uninstalledDate+"','%Y-%m-%d') and DEL_FLAG='0'";
                        JdbcUtil.exeSqlCrud(sqlAmountDefference);

                        //---更新TVM分钱箱表  2021-06-23 去掉钱箱编号更新
                       // String sqlBoxAmountDefference = "update sw_au_tvm_box_amount_difference set CASH_BOX_CODE = '"+moneyBoxCode+"', BOX_UNINSTALL_STATUS = '3', ACTUAL_MONEY = " + uninstallAmount + " *100, diff_money = " + uninstallAmount + " *100 -  SYSTEM_MONEY + HAND_OUT_MONEY, update_time=now()\n" +
                       //         "\t\t  where  line_code = '"+lineCode+"' and station_code = '"+stationCode+"' and tvm_code = '"+tvmCode+"' and RECORD_TIME = DATE_FORMAT('"+uninstalledDate+"','%Y-%m-%d') and  cash_box_type = '"+moneyBoxType+"'";
					   String sqlBoxAmountDefference = "update sw_au_tvm_box_amount_difference set  BOX_UNINSTALL_STATUS = '3', ACTUAL_MONEY = " + uninstallAmount + " *100, diff_money = " + uninstallAmount + " *100 -  SYSTEM_MONEY + HAND_OUT_MONEY, update_time=now()\n" +
                               "\t\t  where  line_code = '"+lineCode+"' and station_code = '"+stationCode+"' and tvm_code = '"+tvmCode+"' and RECORD_TIME = DATE_FORMAT('"+uninstalledDate+"','%Y-%m-%d') and  cash_box_type = '"+moneyBoxType+"' and DEL_FLAG='0'";
                        JdbcUtil.exeSqlCrud(sqlBoxAmountDefference);
                    }
                }
                swStInputCashboxUninstalled.setIsSubmit("1");
                //---更新钱箱未卸载表
                swStInputCashboxUninstalledService.updateById(swStInputCashboxUninstalled);
            }*/
			SwStTvmCheckDetail swStTvmCheckDetail = new SwStTvmCheckDetail();
            swStTvmCheckDetail.setLineCode(lineCode);
            swStTvmCheckDetail.setStationCode(stationCode);
            swStTvmCheckDetail.setTvmCode(tvmCode);
            swStTvmCheckDetail.setRevenueTime(uninstalledDate);
            swStTvmCheckDetail.setDelFlag("0");

            swStTvmCheckDetail = swStTvmCheckDetailService.getOne(Wrappers.query(swStTvmCheckDetail));//钱箱清点主表
            if(ObjectUtil.isNotEmpty(swStTvmCheckDetail)){  
				Integer checkDetailMainId =  swStTvmCheckDetail.getId();
                String tableName  = "";
                if("硬币回收箱".equals(moneyBoxType)){//硬币回收箱
                    tableName="sw_st_tvm_check_detail_coin";
                    moneyBoxType = "1";
                }else if("硬币补充箱".equals(moneyBoxType)){//硬币找零箱
                    tableName="sw_st_tvm_check_detail_coin_change";
                    moneyBoxType = "2";
                }else if("纸币回收箱".equals(moneyBoxType)){  //纸币回收箱
                    tableName="sw_st_tvm_check_detail_paper";
                    moneyBoxType = "3";
                }else if("纸币找零箱".equals(moneyBoxType)){//纸币找零箱
                    tableName="sw_st_tvm_check_detail_paper_change";
                    moneyBoxType = "4";
                }else if("废钞箱".equals(moneyBoxType)){//废钞箱
                    tableName="sw_st_tvm_check_detail_waste";
                    moneyBoxType = "5";
                }

                //-- TODO 如果tvm收入结算未提交，钱箱就已经卸载下来了，就不需要更新收入结算和审核表
                if(!"0".equals(swStTvmCheckDetail.getApprovalStatus())){
                    //---钱箱卸载后更新收入结算清点金额、现金实收金额
                    SwStTvmIncomeSettleDto swStTvmIncomeSettleDto = new SwStTvmIncomeSettleDto();
                    swStTvmIncomeSettleDto.setLineCode(swStTvmCheckDetail.getLineCode());
                    swStTvmIncomeSettleDto.setStationCode(swStTvmCheckDetail.getStationCode());
                    swStTvmIncomeSettleDto.setTvmCode(swStTvmCheckDetail.getTvmCode());
                    swStTvmIncomeSettleDto.setRecordTime(DateUtilStm.LocalDateToUdate(swStTvmCheckDetail.getRevenueTime()));
                    Map<String, Object> stringObjectMap = swStInputCashboxUninstalledMapper.selectCheckAmount(swStTvmIncomeSettleDto);
                    if(ObjectUtil.isNotEmpty(stringObjectMap)){
                      
                        //---更新TVM收入审核主表
                        String sqlAmountDefference = "update sw_au_tvm_amount_defference set BOX_UNINSTALL_STATUS = '3', update_time=now()\n" +
                                "\t\t  where  line_code = '"+lineCode+"' and station_code = '"+stationCode+"' and tvm_code = '"+tvmCode+"' and RECORD_TIME = DATE_FORMAT('"+uninstalledDate+"','%Y-%m-%d') and DEL_FLAG='0'";
                        JdbcUtil.exeSqlCrud(sqlAmountDefference);

                        //---更新TVM分钱箱表  2021-06-23 去掉钱箱编号更新
                       // String sqlBoxAmountDefference = "update sw_au_tvm_box_amount_difference set CASH_BOX_CODE = '"+moneyBoxCode+"', BOX_UNINSTALL_STATUS = '3', ACTUAL_MONEY = " + uninstallAmount + " *100, diff_money = " + uninstallAmount + " *100 -  SYSTEM_MONEY + HAND_OUT_MONEY, update_time=now()\n" +
                       //         "\t\t  where  line_code = '"+lineCode+"' and station_code = '"+stationCode+"' and tvm_code = '"+tvmCode+"' and RECORD_TIME = DATE_FORMAT('"+uninstalledDate+"','%Y-%m-%d') and  cash_box_type = '"+moneyBoxType+"'";
					   String sqlBoxAmountDefference = "update sw_au_tvm_box_amount_difference set  BOX_UNINSTALL_STATUS = '3',update_time=now()\n" +
                               "\t\t  where  line_code = '"+lineCode+"' and station_code = '"+stationCode+"' and tvm_code = '"+tvmCode+"' and RECORD_TIME = DATE_FORMAT('"+uninstalledDate+"','%Y-%m-%d') and  cash_box_type = '"+moneyBoxType+"' and DEL_FLAG='0'";
                        JdbcUtil.exeSqlCrud(sqlBoxAmountDefference);
                    }
                }
                swStInputCashboxUninstalled.setIsSubmit("1");
                //---更新钱箱未卸载表
                swStInputCashboxUninstalledService.updateById(swStInputCashboxUninstalled);
				//更新车站营收日报
				/*
				if(uninstallDate!=null){  //20241105 增加入账日期=实际卸载日期
				    //refreshDailyReport(lineCode,stationCode,uninstallDate);
					String sql  = "update sw_st_reportquery_stationincome set TOTAL = TOTAL+"+uninstallAmount+" where line_code='"+lineCode+"' and station_code='"+stationCode+"' and STATISTICS_DATE='"+DateUtilStm.LocalDateTrunString(uninstallDate)+"'";
                    JdbcUtil.exeSqlCrud(sql);
				    //swStReportQueryController.refreshStationOfIncomeByBox(lineCode,stationCode,DateUtilStm.LocalDateTrunString(uninstallDate));
					
                }*/
            }
        } catch (SQLException e) {
            log.error("{}",e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
			/*
		  点击修改后，根据线路、站点、钱箱编号、钱箱类型、未卸载日期，删除标识，找到钱箱清点记录表，同时记录日志  （小胡接口分析钱箱金额时  1.更新钱箱未卸载的显示金额、差异金额，TVM收入审核表的系统金额、分钱箱审核表的系统金额）
		  1. 更新对应主表的总金额，
		  2. 子表的未卸载原因改为无，卸载金额为输入的金额，非标准币金额为0
		  3. 线路、站点、TVM编号、收益日期、找到收入结算表的最新一条数据，将清点金额、现金实收金额更新 
		  4. 找到TVM收入审核主表，（线路、站点、收益日期、TVM编号，重新计算对应的金额
		  5. 分钱箱审核表，根据线路、站点、收益日期、TVM编号、钱箱编号，重新计算对应的金额，将卸载状态改为未卸载/已卸载
        

		  1.
		   先找到主表，然后根据主表ID查找几个子表，重新计算总金额
		   （一个子表只能有一条记录）
		  
		  2 根据1中，找到主表ID，更新主表的同时，把未卸载金额同时累加到合计中
		    int mainId=XX;
			BigDecimal totalSum==重新计算后的总金额 ;
		  
         // //3,4,5先查询收入审核表中原来的补币，手工清出金额，然后把钱箱清点实际金额根据公式重新计算
		 select SUPPLEMENT_MONEY/100 as '补币金额',HAND_OUT_MONEY/100 as '手工清出金额',SYSTEM_MONEY/100 as '系统金额' from sw_au_tvm_amount_defference
         where line_code=? and station_code=? and tvm_code=? and DATE_FORMAT(RECORD_TIME,'%Y-%m-%d')=?
        
        //更新收入结算表金额 sw_st_tvm_income_settle表中的cash_Receipt_Amount = check_Amount-补币+手工清出 
		//.update sw_st_tvm_income_settle set check_Amount=（2中的清点合计金额totalSum）,cash_Receipt_Amount =totalSum-补币+手工清出,update_time=now() 
         //更新TVM收入审核主表sw_au_tvm_box_amount_difference表中的ACTUAL_MONEY = 实际卸载金额
          update sw_au_tvm_amount_defference set BOX_UNINSTALL_STATUS='3' (未卸载/已卸载), actual_money=(totalSum-补币金额+手工清出金额)*100,diff_money=(totalSum-补币金额+手工清出金额)*100-系统金额，update_time=now()
		  where  line_code=? and station_code=? and tvm_code=? and DATE_FORMAT(RECORD_TIME,'%Y-%m-%d')=?
        //更新TVM分钱箱表,需要验证下，数据库视图是否支持未卸载已卸载的问题，如果不支持，状态统一改为已卸载。
		update sw_au_tvm_box_amount_difference set BOX_UNINSTALL_STATUS='3',ACTUAL_MONEY=uninstallAmount*100,diff_money=uninstallAmount*100-系统金额
        where  line_code=? and station_code=? and tvm_code=? and RECORD_TIME=? and  cash_box_type=? and cash_box_code=?
     
		
		 //sw_au开头的表，金额都是乘以100的。
			
        

		*/
        return R.ok();
    }

    /**
     * 通过id删除钱箱未卸载
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除钱箱未卸载", notes = "通过id删除钱箱未卸载")
    @SysLog("通过id删除钱箱未卸载")
    @DeleteMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('swstinputcashboxuninstalled_del')")
    public R removeById(@PathVariable Integer id) {
        return R.ok(swStInputCashboxUninstalledService.removeById(id));
    }


    /**
     * 批量删除子表
     *
     * @param idList
     * @return
     */
    @SysLog("通过id删除钱箱未卸载")
    @DeleteMapping("/batchCascadeDel")
    //@PreAuthorize("@pms.hasPermission('swstinputcashboxuninstalled_batch_del')")
    @Transactional
    @ApiOperation(value = "通过id删除钱箱未卸载", notes = "通过id删除钱箱未卸载")
    public R batchRemoveById(@RequestBody List<Integer> idList) {
        List<SwStInputCashboxUninstalled> list = swStInputCashboxUninstalledService.list(new QueryWrapper<SwStInputCashboxUninstalled>().lambda().in(SwStInputCashboxUninstalled::getId, idList));
        List<Integer> deleteIds = list.stream().filter(x -> !x.getIsSubmit().equals(CommonConstants.SUBMIT)).map(x -> x.getId()).collect(Collectors.toList());
        deleteIds.forEach(swStInputCashboxUninstalledService::removeById);
        return R.ok();
    }

    @ApiOperation(value = "导出钱箱未卸载数据", notes = "导出钱箱未卸载数据")
    @GetMapping("/export")
    public void export(Page page, SwStInputCashboxUninstalled swStInputCashboxUninstalled, HttpServletResponse response) {
        List<SwStInputCashboxUninstalled> records = swStInputCashboxUninstalledService.page(page, Wrappers.query(swStInputCashboxUninstalled)).getRecords();
        try {
            R<List<SysDictItem>> inputDataStatus = systemUserService.getDictByType(StmConstans.STM_INPUT_DATA_STATUS);
            R<List<SysDictItem>> cashBoxType = systemUserService.getDictByType(StmConstans.STM_CASH_BOX_TYPE);
            List<SysDictItem> dictData = inputDataStatus.getData();
            List<SysDictItem> cashBoxDictData = cashBoxType.getData();
            if (CollectionUtil.isNotEmpty(records)) {
                Map<String, String> map = dictData.stream().collect(Collectors.toMap(SysDictItem::getValue, SysDictItem::getLabel));
                Map<String, String> cashBoxDataMap = cashBoxDictData.stream().collect(Collectors.toMap(SysDictItem::getValue, SysDictItem::getLabel));
                for (SwStInputCashboxUninstalled record : records) {
                    record.setIsSubmit(map.get(record.getIsSubmit()));
                    record.setMoneyBoxType(cashBoxDataMap.get(record.getMoneyBoxType()));
                }
            }
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("钱箱未卸载数据", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + System.currentTimeMillis() + ".xlsx");
            EasyExcel.write(response.getOutputStream(), SwStInputCashboxUninstalled.class).
                    sheet("钱箱未卸载数据").doWrite(records);
        } catch (IOException e) {
            log.error("钱箱未卸载导出失败");
        }
    }
}
